package 力扣;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 例如：
 给定二叉树 [3,9,20,null,null,15,7],
  3
 / \
 9  20
 /  \
 15   7
 返回其自底向上的层次遍历为：
 [
 [15,7],
 [9,20],
 [3]
 ]
 */

public class _107二叉树的层次遍历_II {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    // 思路 返回一个LinkedList 每次将结果放到队列的头
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if( root == null ) return new ArrayList<List<Integer>>();
        LinkedList<List<Integer>> lists = new LinkedList<List<Integer>>();
        LinkedList<TreeNode> quque = new LinkedList<>();
        quque.add(root);
        while( !quque.isEmpty() ){
            ArrayList<Integer> list = new ArrayList<>();
            int size = quque.size();
            while( size>0 ){
                TreeNode node = quque.poll();
                list.add(node.val);
                if( node.left !=null ){
                    quque.add(node.left);
                }
                if( node.right !=null ){
                    quque.add(node.right);
                }
                size--;
            }
            lists.addFirst(list);
        }

        return lists;
    }
}
